/*
 * 该js文件专门用于存放通用的方法(包括查询页面、单据页面等)
 * */
//所有dom加载完后执行，类似页面launch
// 获取上传地址
var updateurls;
/*
$.get('/system/fileinfo/selectFileSystem?moduleFile=images', function (res) {
    if (res.code == 0) {
        var data = JSON.parse(res.data)
        updateurls = data.uploadUrl
    }
});
*/
(function () {
    var layid = top.$("[lay-filter='layadmin-layout-tabs']").find('.layui-this').attr('lay-id');//记录当前tabid，防止快速点击切换其他tab页面
    setTimeout(function () {//1S后进行身份验证，否则关闭遮罩
        var noAuthentication = true;//默认无需身份验证
        if (parent == top) {//父页面是框架页面，即当前页面是tab页（非弹出层）
        	/*
            $.each(top.session.authenticationModuleMap, function (i, v) {//循环限定查询功能对象
                if (typeof moduleTable == 'string' && moduleTable.split('GROUP')[0].toLocaleUpperCase() == i) { //页面存在moduleTable对象，并且是限定查询功能（整单moduleTable需要切割）
                    noAuthentication = false;
                    if ($.cookie('dhecp_' + moduleTable.split('GROUP')[0])) {//更新解锁功能cookie，并关闭加载动画
                        top.$('.page-loading').hide();
                        $.cookie('dhecp_' + moduleTable.split('GROUP')[0], true, {
                            expires: new Date(new Date().getTime() + (1000 * 60 * Number(top.session.systemSet.passwordPeriodMM))),
                            path: '/'
                        });
                    } else top.lockModule(layid, v, moduleTable.split('GROUP')[0], top.session.systemSet.passwordPeriodMM);//未解锁功能则验证
                }
            })
            */
        }
        if (noAuthentication) top.$('.page-loading').hide();
    }, 1000)
    $(document).on("mouseenter", "*[lay-tips]", function () {
        var e = $(this);
        var i = e.attr("lay-tips"),
            t = e.attr("lay-offset"),
            n = e.attr("lay-direction") || 1,
            l = layer.tips(i, this, {
                tips: n,
                time: -1,
                success: function (lt, a) {
                    t && lt.css("margin-left", t + "px");
                    tipsOverFlow(lt, n, e.offset());
                }
            });
        e.data("index", l)
    }).on("mouseleave", "*[lay-tips]", function () {
        layer.close($(this).data("index"))
    });

    function tipsOverFlow(e, n, t) {
        switch (Number(n)) {
            case 1://上
                if (e.offset().top < 0) {
                    e.width(e.width() + 100);
                    e.offset({top: t.top - e.height() - 10});
                    if (e.offset().top < 0) tipsOverFlow(e, n, t);
                }
                break;
            case 2://右
            case 3://下
                if (e.height() + e.offset().top > window.innerHeight) {
                    e.width(e.width() + 100);
                    if (e.height() + e.offset().top > window.innerHeight) tipsOverFlow(e, n, t);
                }
                break;
            case 4://左
                if (e.height() + e.offset().top > window.innerHeight) {
                    e.width(e.width() + 100);
                    e.offset({left: t.left});
                    e.offset({left: t.left - e.width() - 10});
                    if (e.height() + e.offset().top > window.innerHeight) tipsOverFlow(e, n, t);
                }
            default:
                break;
        }
    }
})(jQuery);
//修改Date构造器，转换传输时间字符串中的字符
//mac safari浏览器不识别new Date('yyyy-MM-dd HH:mm:ss')，需要转换成yyyy/MM/dd HH:mm:ss或yyyy-MM-ddTHH:mm:ss。
Date = function (Date) {
    ReDate.prototype = Date.prototype;
    // 将Date构造器的属性方法，复制到ReDate构造器上
    var propertys = Object.getOwnPropertyNames(Date.prototype.constructor);
    if (propertys && propertys.length > 0) {
        for (var i = 0; i < propertys.length; i++) {
            var name = propertys[i];
            ReDate[name] = Date.prototype.constructor[name];
        }
    }
    return ReDate;

    function ReDate() {
        // 当只有一个参数并且参数类型是字符串时，把字符串中的-替换为/
        if (arguments.length === 1) {
            let arg = arguments[0];
            if (Object.prototype.toString.call(arg) === '[object String]' && arg.indexOf('T') === -1) {
                arguments[0] = arg.replace(/-/g, "/");
            }
        }
        let bind = Function.bind;
        let unbind = bind.bind(bind);
        return new (unbind(Date, null).apply(null, arguments));
    }
}(Date);
//var logo_color = window.localStorage.getItem('layuiAdmin') ? JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.logo : '#F78400';
//$('.layui-elem-quote').attr('style', 'border-left-color:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
//$('.layui-elem-quote').attr('style','border-color:'+logo_color);
// $('.layui-tab-title li').css({"background":"#fff","color":"#666666","border": "1px solid" ,"border-color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"margin-right": "-1px"});
// $('.layui-tab-title .layui-this').css({"color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"background":"#fff","border": "1px solid" ,"border-color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"border-bottom": "1px solid #fff","margin-right": "-1px"});
// $('.layui-tab-title-one li').css('style','background:#e5e5e5;');
// $('.layui-tab-title-one .layui-this').css('style','background:#fff;');

//$('.layui-tab-title li').attr('style','background:#fff;color:#666666;border: 1px solid ;margin-right: -1px;');
//$('.layui-tab-title li').css('border-color',JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
//$('.layui-tab-title .layui-this').attr('style','background:#fff;border: 1px solid ;margin-right: -1px;');
//$('.layui-tab-title .layui-this').css({"color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"border-color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"border-bottom-color":"#FFF"});
//$('.layui-tab-title-one li').attr('style','background:#e5e5e5;');
//$('.layui-tab-title-one .layui-this').attr('style','background:#fff;');

//$('.layui-tab-title').attr('style', 'border-color:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
$('.layui-tab-title li').attr('style', 'background:#fff;color:#666666');
//$('.layui-tab-title .layui-this').attr('style', 'color:#fff;background:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
//$('.layui-tab-title .layui-this').css('border-color', JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
$('.layui-tab-title-one li').attr('style', 'background:#e5e5e5;');
//$('.layui-tab-title-one .layui-this').attr('style', 'color:#fff;background:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
//$('.layui-tab-title-one .layui-this').css('border-color', JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
//Tab选项卡修改背景颜色
$(document).on('click', '.layui-tab-title', function (event) {
    // $('.layui-tab-title .layui-this').attr('style','color:#000;background:'+logo_color);
    //$('.layui-tab-title li').css({"background":"#fff","color":"#666666","border": "1px solid","border-color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"margin-right": "-1px"});
    //$('.layui-tab-title .layui-this').css({"color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"background":"#fff","border": "1px solid","margin-right": "-1px","border-color":JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header,"border-bottom-color":"#FFF"});
    //$('.layui-tab-title-one li').attr('style','background:#e5e5e5;');
    //$('.layui-tab-title-one .layui-this').attr('style','background:#fff;');
    //$('.layui-tab-title').attr('style', 'border-color:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
    $('.layui-tab-title li').attr('style', 'background:#fff;color:#666666');

    // if(['TCG_PURCHASEORDER'].includes(moduleTable)){
    // 	$('.layui-tab-title li').attr('style','background:#fff;color:#666666');
    // }else{
    // 	$('.layui-tab-title li').attr('style','background:#fff;color:#666666');
    // 	$('.layui-tab-title li').eq(1).hide();
    // }

    $('.layui-tab-title-one li').attr('style', 'background:#e5e5e5;');
    //$('.layui-tab-title .layui-this').attr('style', 'color:#fff;background:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
    //$('.layui-tab-title .layui-this').css('border-color', JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);

})
// JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header
//Tab选项卡修改背景颜色/任务中心
$(document).on('click', '.layui-tab-title-one', function (event) {
    console.log("切换流程")
    $('.layui-tab-title-one li').attr('style', 'background:#e5e5e5;');
    //$('.layui-tab-title-one .layui-this').attr('style', 'color:#fff;background:' + JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
    //$('.layui-tab-title-one .layui-this').css('border-color', JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.header);
})
//数值框输入限制大小
$("input[type='number']").blur(function (obj) {
    if (!!obj.currentTarget.min && Number(obj.currentTarget.value) < Number(obj.currentTarget.min)) obj.currentTarget.value = obj.currentTarget.min;
    if (!!obj.currentTarget.max && Number(obj.currentTarget.value) > Number(obj.currentTarget.max)) obj.currentTarget.value = obj.currentTarget.max;
})
//tree表格树 展开/折叠
var expandFlag;
$("#expandAllBtn").click(function () {
    var dataExpand = $.common.isEmpty($.tablelist._option.expandAll) ? true : $.tablelist._option.expandAll;
    expandFlag = $.common.isEmpty(expandFlag) ? dataExpand : expandFlag;
    if (!expandFlag) {
        $.bttTable.bootstrapTreeTable('expandAll');
    } else {
        $.bttTable.bootstrapTreeTable('collapseAll');
    }
    expandFlag = expandFlag ? false : true;
});

//获取当前日期
function getDate() {
    var newDate = new Date;
    var year = newDate.getFullYear();	//获取当前年
    var mon = newDate.getMonth() + 1;	//获取当前月
    var date = newDate.getDate();		//获取当前日
    var week = newDate.getDay();
    return year + "-" + appendZero(mon) + "-" + appendZero(date);
}

//获取当前日期时间
function getTime() {
    var newDate = new Date;
    var year = newDate.getFullYear();	//获取当前年
    var mon = newDate.getMonth() + 1;	//获取当前月
    var date = newDate.getDate();		//获取当前日
    var h = newDate.getHours();			//获取当前小时数(0-23)
    var m = newDate.getMinutes();		//获取当前分钟数(0-59)
    var s = newDate.getSeconds();		//获取当前秒
    var week = newDate.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    return year + "-" + appendZero(mon) + "-" + appendZero(date) + " " + appendZero(h) + ":" + appendZero(m) + ":" + appendZero(s);
}

/*
 * 转化时间格式
 * param：dateTime 时间对象
 * param：returnType 转化类型，默认为长日期格式‘yyyy-MM-dd HH:mm:ss’
 * return: 时间字符串
*/
function formatDate(dateTime, returnType = 'datetime') {
    var year = dateTime.getFullYear();	//获取当前年
    var mon = dateTime.getMonth() + 1;	//获取当前月
    var date = dateTime.getDate();		//获取当前日
    var h = dateTime.getHours();		//获取当前小时数(0-23)
    var m = dateTime.getMinutes();		//获取当前分钟数(0-59)
    var s = dateTime.getSeconds();		//获取当前秒
    var week = dateTime.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    switch (returnType) {
        case 'datetime':
            return year + "-" + appendZero(mon) + "-" + appendZero(date) + " " + appendZero(h) + ":" + appendZero(m) + ":" + appendZero(s);
        case 'date':
            return year + "-" + appendZero(mon) + "-" + appendZero(date);
        case 'year':
            return year;
        case 'month':
            return year + "-" + appendZero(mon);
    }
}

//时间相关——补全两位数
function appendZero(obj) {
    if (obj < 10) return "0" + obj; else return obj;
}

//"10/1/19" 转 "2019-10-01"
function forDate(d) {
    var date = new Date(d);
    return date.getFullYear() + "-" + ((parseInt(date.getMonth()) + 1 > 9) ? (parseInt(date.getMonth()) + 1) : "0" + (parseInt(date.getMonth()) + 1)) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate());
}

//验证是年份——形如：2020
function judgeStrYear(str) {
//	var r = str.match(/^(\d{1,4})(-)(\d{1,2})\2(\d{1,2})$/);
    var r = str.match(/^(\d{1,4})$/);
    if (r == null) return false;
    var d = new Date(r[1]);
    return (d.getFullYear() == r[1]);
}

//验证是否短日期——形如：2020-01-01
function judgeStrDate(str) {
//	var r = str.match(/^(\d{1,4})(-)(\d{1,2})\2(\d{1,2})$/);
    var r = str.match(/^(\d{1,4})(-|\/|.)(\d{1,2})\2(\d{1,2})$/);
    if (r == null) return false;
    var d = new Date(r[1], r[3] - 1, r[4]);
    return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]);
}

//验证是否长时间——形如 ：2020-01-01 00:00:00
function judgeStrDateTime(str) {
//	var reg = /^(\d{1,4})(-|)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
    var reg = /^(\d{1,4})(-|\/|.)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
    var r = str.match(reg);
    if (r == null) return false;
    var d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
    return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6] && d.getSeconds() == r[7]);
}

//序列化表单字段为json对象
$.fn.serializeFormToJson = function () {
    var arr = $(this).serializeArray();//form表单数据 name：value
    var param = {};
    $.each(arr, function (i, obj) { //将form表单数据封装成json对象
        param[obj.name] = obj.value;
    })
    return param;
}

//弹出列设置框、操作
function filedSet(moduleTable) {
    layer.config({
        extend: 'myskin/style.css', //加载扩展样式
    });
    layer.open({
        type: 2,
        skin: 'reset-class',
        area: ['620px', '550px'],
        offset: '6%',//距离顶部
        fix: false,
        maxmin: true,
        shade: 0.6,
        title: '列设置',
        content: '/system/userdefinedfields?moduleTable=' + moduleTable,
        btn: ['确定', '重置', '关闭'],
        shadeClose: true,
        yes: function (index) {
            var res = window["layui-layer-iframe" + index].callbackdata();
            $.operate.post('/system/userdefinedfields/editpost', {
                'infoItems': JSON.stringify(res),
                'moduleTable': moduleTable
            }, function (result) {
                setTimeout(function () {
                    window.location.reload();
                }, 1500);
            });
        }
        , btn2: function (index, layero) {
            $.modal.confirmCom('确认要恢复系统设置（删除用户自定义设置列）吗？', function (index) {
                $.operate.post('/system/userdefinedfields/resetpost', {'moduleTable': moduleTable}, function (result) {
                    setTimeout(function () {
                        window.location.reload();
                    }, 1500);
                });
            });
            return false;
        },
        cancel: function (index) {
            return true;
        }
    });
    /*$.modal.open('列设置','/system/userdefinedfields?moduleTable='+moduleTable,'620','550',function(index){
		var res = window["layui-layer-iframe" + index].callbackdata();
			$.operate.post('/system/userdefinedfields/editpost',{'infoItems':JSON.stringify(res),'moduleTable':moduleTable},function(result){
			setTimeout(function(){
				window.location.reload();
			}, 1500);
		});
 	}) */
}

//加载中
function showloadings(t) {
    if (t) {//如果是true则显示loading
        layer.load(2, {
            shade: [0.1, '#000'] //0.1透明度的白色背景
        });
    } else {//如果是false则关闭loading
        layer.closeAll('loading');
    }
}

//添加搜索条件
function addMore(obj) {
    appendSearch(obj, 1);
    //删除条件
    $(".remove-this").click(function () {
        $(this).parents('.layui-col-xs3').remove();
    })
}

/*
 * 生成查询条件代码
 * param:obj 下拉对象
 * param:where 添加位置（1：顶部、2：右侧）
 */
function appendSearch(obj, where) {
    var select = $('#condition option:selected');
    var key = select.val().replace(select.val()[0], select.val()[0].toLowerCase());//首字母小写
//    	if(key.substring(key.length-4,key.length)=='Name')key=key.substring(0,key.length-4);//虚拟字段切割？客户属性、供应商属性
    if (document.getElementById(key)) {//通过id查找是否存在相同id
        layer.msg("该查询条件已存在！");
        return;
    }
    switch (where) {//判断添加位置
        case 1://顶部（xs3样式）
            wherestr[key] = '';//给该条件的查询语句占坑
            var str = "<div class='layui-inline layui-col-xs3'><label class='layui-form-label'>" + select.text() + "：</label><div class='layui-input-block'>";
            break;
        case 2://右侧（查询列表）
            if (select.attr('fft') == 't_text' && select.attr('ffct') == 't_between') {
                var str = "<div class='layui-form-item item-height'><label class='layui-form-label'>" + select.text() + "从：</label><div class='layui-input-block'>";
            } else {
                var str = "<div class='layui-form-item'><label class='layui-form-label'>" + select.text() + "：</label><div class='layui-input-block'>";
            }
            break;
        default:
            layer.msg("添加位置参数为空！");
            break;
    }
    switch (select.attr('fft')) {
        case 't_text'://文本输入框
        case 't_decimal'://数值输入框
            if (select.attr('ffct') != 't_between') {
                str += "<input type=" + (select.attr('fft') == "t_text" ? "text" : "number") + " name='" + key + "' id='" + key + "' autocomplete='off' class='layui-input search-field' fft='t_text'><a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            } else {
                str += "<input type=" + (select.attr('fft') == "t_text" ? "text" : "number") + " name='" + key + "_s' id='" + key + "_s' autocomplete='off' class='layui-input search-field' fft='t_text'><a class='dhicon dh-times-circle-o remove-this' style='margin-top: -7px;'>&nbsp;</a></div>";
                str += "<label class='layui-form-label'>到：</label><div class='layui-input-block'>";
                str += "<input type=" + (select.attr('fft') == "t_text" ? "text" : "number") + " name='" + key + "_e' id='" + key + "_e' autocomplete='off' class='layui-input search-field' fft='t_text'></div></div>";
            }
            break;
        case 't_date'://日期选择框
            str += "<input type='text' class='layui-input search-field' id='" + key + "' name='" + key + "' autocomplete='off' placeholder='请选择时间范围' fft='t_date' ffct='" + select.attr('ffct') + "'>";
            str += "<i class='dhicon dh-calendar icon_date_business'></i><a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
        case 't_datetime'://日期时间选择框
            str += "<input type='text' class='layui-input search-field' id='" + key + "' name='" + key + "' autocomplete='off' placeholder='请选择时间范围' fft='t_datetime' ffct='" + select.attr('ffct') + "'>";
            str += "<i class='dhicon dh-calendar icon_date_business'></i><a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
        case 't_checkcondition'://复选框(查询时处于选中状态则该字段传值为1，未选中状态下不传值)
            var checkedStr = '';
            if (select.attr('fieldDefault')) checkedStr = "checked";
            str += "<input type='checkbox' lay-skin='primary' class='search-field' id='" + key + "' name='" + key + "' fft='t_checkcondition' " + checkedStr + "><a class='dhicon dh-times-circle-o remove-this' style='margin-top: 10px;'>&nbsp;</a></div></div>";
            break;
        case 't_buttontext'://弹出框
        case 't_buttontextedit'://可编辑弹出框
            str += "<input type='text' class='layui-input search-field buttontext' id='" + key + "' name='" + key + "' getType='" + key + "'/>";
            str += "<i class='layui-icon layui-icon-more getMore' onclick=\"getMore(\'" + key + "\',null,\'" + select.attr('text') + "\',\'" + select.attr('fst') + "\',true);\"></i>";
            str += "<a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
        /*case 't_textarea'://文本区域
			break;*/
        case 't_radio'://单选按钮
            if (key.indexOf("userSex") == 0) {
                str += '<div><input type="radio" id=' + key + ' name=' + key + ' value="男" title="男" class="search-field" fft="t_radio"><input type="radio" name=' + key + ' value="女" title="女"></div>';
            } else {
                str += '<div><input type="radio" id=' + key + ' name=' + key + ' value="0" title="否" class="search-field" fft="t_radio"><input type="radio" name=' + key + ' value="1" title="是"></div>';
            }
            str += "<a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
        case 't_checkbox':
            str += '<div><input type="radio" id=' + key + ' name=' + key + ' value="0" title="否" class="search-field" fft="t_radio"><input type="radio" name=' + key + ' value="1" title="是"></div>';
            str += "<a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
        case 't_dropdown'://下拉框——html代码写在页面上
            str += $('#dropdown_' + key).text();
            str += "<a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
        default://默认输入框
            str += "<input type='text' name='" + key + "' id='" + key + "' autocomplete='off' class='layui-input search-field'><a class='dhicon dh-times-circle-o remove-this'>&nbsp;</a></div></div>";
            break;
    }
    $(obj).parents('.layui-form').find('.append-this').before(str);
    if (select.attr('fft') == 't_date') {//是日期则需要渲染
        if (select.attr('ffct') == 't_between') laydate.render({
            elem: '#' + key,
            type: 'date',
            trigger: 'click',
            range: '~'
        });
        else laydate.render({elem: '#' + key, type: 'date', trigger: 'click'});
    }
    if (select.attr('fft') == 't_datetime') {//是日期则需要渲染
        if (select.attr('ffct') == 't_between') laydate.render({
            elem: '#' + key,
            type: 'datetime',
            trigger: 'click',
            range: '~'
        });
        else laydate.render({elem: '#' + key, type: 'datetime', trigger: 'click'});
    }
    form.render();
}

//键盘控制上下左右
document.onkeydown = function (event) {
    var td_obj = $('.layui-table-edit').parent();
    var e = event || window.event || arguments.callee.caller.arguments[0];
    var data_field = td_obj.attr('data-field');
    if (e && e.keyCode == 38) { // 上
        var $nextTr = td_obj.parents('tr').prev();
        if ($nextTr.length) {
            $nextTr.children('[data-field="' + data_field + '"]').trigger('click');
        }
    }
    if (e && e.keyCode == 40) { //下
        var $nextTr = td_obj.parents('tr').next();
        if ($nextTr.length) {
            $nextTr.children('[data-field="' + data_field + '"]').trigger('click');
        }
    }
    if (e && e.keyCode == 37) { // 左
        var $nextTr = td_obj.prev();
        if ($nextTr.length) {
            $nextTr.trigger('click');
        }
    }
    if (e && e.keyCode == 39) { // 右
        var $nextTr = td_obj.next();
        if ($nextTr.length) {
            $nextTr.trigger('click');
        }
    }
}

//跳转指定链接
function goUrl(url) {
    setTimeout(function () {
        window.location.href = url;
    }, 1000);
}

//数据表格点击行时，添加背景颜色
$(document).on('click', '.layui-table-view .layui-table-body tr', function (event) {
    var trElem = $(this);
    var tableView = trElem.closest('.layui-table-view');
    tableView.find('.layui-table-body tr.table_tr_click').removeClass('table_tr_click');
    // tableView.find('.layui-table-body tr[data-index="' + trElem.data('index') + '"]').addClass('table_tr_click');
})
//焦点在数据表格的输入控件时，触发点击行事件
$(document).on('focus', '.layui-table-view .layui-table-body input', function (event) {
    $(this).closest('tr').click();
})

//获取表格选中行数据
function getTableSelect(tableId) {
    var tableSelectTr = $('[lay-id=' + tableId + '] .table_tr_click');
    if (tableSelectTr.length) return table.cache[tableId][tableSelectTr[0].dataset.index];
    else $.modal.msgWarning('未选中数据！');
}

//失去焦点方法
function inputOnBlur(obj) {
    $.each(k_fields, function (i, v) {//移除其他必填项未填提示
        if (v.fieldFrontRequired) $('#' + v.fields).css('border', '');
    })
    if ($(obj).val().length < 1) obj.style.border = '1px solid red';
    else obj.style.border = '';
}

//明细附件列表
function detailUpload() {
    $(".getDetailUpload").click(function () {
        var fileMark = $(this).attr("tGuid"),
            fieldName = $(this).attr("tName"),
            forObj = $(this).parent().find('span');

        var obj = $(this);
        getUpload(fieldName, "Detail", fileMark, forObj);
    })
}

/*
 * 获取单据附件列表
 * param:fieldName 附件字段名
 * param:vType 类型Head
 * param:fileMark 单据整单附件:nid、单据明细附件:guid、打印报表:moduletable值
 * param:forObj 赋值对象
 */
function getUpload(fieldName, vType = "Head", fileMark = "", forObj = "", fieldFrontValue = "") {

    var nid = $("#nid").val(),
        flag = true, forSet = '';
    if (vType == "Detail" && fileMark == "undefined") {
        flag = false;
        layer.msg("新增明细需保存单据后，才能上传附件！");
    }
    debugger

    if (flag) {
        if (nid != '0') {
            if (fieldFrontValue) {
                var fieldFrontArr = fieldFrontValue.split(",");
                fileMark = $("#" + fieldFrontArr[0]).val()
                if (fieldFrontArr.length == 2) fieldName = fieldFrontArr[1]
            } else {
                if (!fileMark) fileMark = nid;
            }
            if (!fileMark) return;
            var mTitle = '附件列表',
                mUrl = '/system/fileinfo/add?moduleFile=attach&vType=' + vType + '&fileMark=' + fileMark + '&fieldName=' + fieldName + '&moduleTable=' + moduleTable,
                mWidth = '800', mHeight = '410';
        } else {
            flag = false;
            layer.msg("保存单据后，才能上传附件！");
        }
        if (flag) {
            $.modal.openSimple(mTitle, mUrl, mWidth, mHeight, function (index) {
                var res = window["layui-layer-iframe" + index].callbackdata();
                if (res) {
                    forSet = res + '个附件';
                } else {
                    forSet = '无附件';
                }
                if (forObj) {//判断是否明细（控件无id）
                    forObj.html(forSet)
                } else {
                    $("#" + fieldName).val(forSet);
                }
                layer.close(index);
            });
        }
    }
}

function getReport() {
    var mTitle = '打印模板列表',
        mUrl = '/system/fileinfo/add?moduleFile=report&vType=Report&fileMark=' + moduleTable + '&fieldName=Report&moduleTable=' + moduleTable,
        mWidth = Number($(window).width()) < 775 ? $(window).width() : 775,
        mHeight = Number($(window).height()) < 400 ? $(window).height() : 400;
    $.modal.openSimple(mTitle, mUrl, mWidth, mHeight);
}

/*
 * 客户、供应商获取单据附件列表
 * param:fieldName 附件字段名
 * param:vType 类型Head
 * param:fileMark 客户、供应商编号
 * param:forObj 赋值对象
 */
function getUploadCommon(fieldName, vType = "Head", fileMark = "", forObj = "") {
    var flag = true, forSet = '';
    if (flag) {
        if (fileMark != null) {
            var mTitle = '附件列表',
                mUrl = '/system/fileinfo/add?moduleFile=attach&vType=' + vType + '&fileMark=' + fileMark + '&fieldName=' + fieldName + '&moduleTable=' + moduleTable,
                mWidth = '680', mHeight = '400';
        } else {
            flag = false;
            layer.msg("保存后，才能上传附件！");
        }
        if (flag) {
            $.modal.openSimple(mTitle, mUrl, mWidth, mHeight, function (index) {
                var res = window["layui-layer-iframe" + index].callbackdata();
                if (res) {
                    forSet = res + '个附件';
                } else {
                    forSet = '无附件';
                }
                if (forObj) {
                    forObj.val(forSet)
                } else {
                    $("#" + fieldName).val(forSet);
                }
                layer.close(index);
            });
        }
    }
}

//JS函数用于获取url参数
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

//切割url提取参数并返回成map数组格式,默认传入window.location.search获取url地址?至结尾的所有参数
function getUrlSearchToArray(Url) {
    var str = Url;// 获取URL中?之后的字符
    str = str.substring(1, str.length);
    var arr = str.split("&");//以&分隔字符串,获得类似key=value格式的元素数组
    var obj = new Object();
    for (var i = 0; i < arr.length; i++) {// 将每一个数组元素以=分隔并赋给obj对象
        var tmp_arr = arr[i].split("=");
        obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
    }
    return obj;
}

//失去焦点时刷新重新渲染下拉框
function refreshSelect() {
    setTimeout(function () {//防止选中下拉项而不更新
        form.render('select');//修复下拉框选中后无法消失的问题
    }, 100);
}

//数据表格重新赋值小数位数——显示类型、系统设置
function decimalToFixed(listData, decimalObj) {
    if (listData && listData.length) $.each(listData, function (v, k) {
        $.each(decimalObj, function (v2, k2) {
            k[v2] = Number(k[v2] ? k[v2] : 0).toFixed(k2);
        })
    })
    return listData;
}

//修复合计行固定列问题及固定合计行小数位
function fixTotal(myTable) {
    // if(gridColumns.gridBody[0].type=="numbers")gridColumns.gridBody[0]={"type": "numbers","fixed": "left"};//重新定义序号列，以便翻页重新计算序号列宽度
    var $table = $(myTable.elem),
        $total = $table.next().children('.layui-table-total');
    if ($total.length > 0) { //存在合计行
        if ($total.find('table')[0]) {
            $.each($($total.find('table')[0]).find('td'), function (i, v) {
                if ($(v).data('field') in gridColumns.decimalObj && $(v).text()) $(v).children().text(Number($(v).text()).toFixed(gridColumns.decimalObj[$(v).data('field')]))
            })
        }
        if ($total.find('table').length > 1) { //合计行存在固定列
            $total.find('table')[1].remove();
        }
        var $tableBox = $table.next().children('.layui-table-box'),
            $fixedLeft = $tableBox.children('.layui-table-fixed-l').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
            $fixedRight = $tableBox.children('.layui-table-fixed-r').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
            html = [];
        if ($fixedLeft.length > 0) {
            $table.next().find('style').append('.layui-table-total-fixed-l .layui-table-patch{display: none}');
            $table.next().css('position', 'relative');
            $('.layui-table-total').attr('style', 'position: relative;')
            html.push('<table style="position: absolute;background: #fff;left: 0;top:0px" cellspacing="0" cellpadding="0" border="0" class="layui-table layui-table-total-fixed layui-table-total-fixed-l"><tbody><tr>');
            $fixedLeft.each(function (i) {
                if ($(this).data('key')) {
                    if (i == 0) html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML").split('</div></td>')[0] + '合计</div></td>');
                    else {
                        var tdText = $total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').text();
                        if ($(this).data('field') in gridColumns.decimalObj && tdText) {
                            tdText = Number(tdText).toFixed(gridColumns.decimalObj[$(this).data('field')]);
                            $total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').children().text(tdText);
                        }
                        html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"));
                    }
                }
            })
            html.push('</tr></tbody></table>');
            $total.append(html.join(''))
        }
        if ($fixedRight.length > 0) {
            $table.next().find('style').append('.layui-table-total-fixed-r td:first-child{border-left:1px solid #e6e6e6}.layui-table-total-fixed-r td:last-child{border-left: none}');
            $table.next().css('position', 'relative');
            html = [];
            html.push('<table style="position: absolute;background: #fff;right: 0;top: ' + ($total.position().top + 1) + 'px" cellspacing="0" cellpadding="0" border="0" class="layui-table layui-table-total-fixed layui-table-total-fixed-r"><tbody><tr>');
            $fixedRight.each(function () {
                html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"));
            })
            html.push('</tr></tbody></table>');
            $total.append(html.join(''));
        }
    }
}

function rowheight(index, layero) {
    //表头部分
    //动态监听表头高度变化，冻结行跟着改变高度
    $(".layui-table-header  tr").resize(function () {
        $(".layui-table-header  tr").each(function (index, val) {
            $($(".layui-table-fixed .layui-table-header table tr")[index]).height($(val).height());
        });
    });
    //初始化高度，使得冻结行表头高度一致
    $(".layui-table-header  tr").each(function (index, val) {
        $($(".layui-table-fixed .layui-table-header table tr")[index]).height($(val).height());
    });

    //表体部分
    //动态监听表体高度变化，冻结行跟着改变高度
    $(".layui-table-body  tr").resize(function () {
        $(".layui-table-body  tr").each(function (index, val) {
            $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
        });
    });
    //初始化高度，使得冻结行表体高度一致
    $(".layui-table-body  tr").each(function (index, val) {
        $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
    });
}

$('body').on('click', '.layui-table-cell', function () {
    var tcval = $(this).text()
    sessionStorage.setItem('tcval', tcval)
})

/*
 * 弹出框打开与赋值
 * parma:fields 目标字段
 * parma:tindex 单据明细中的下标
 * parma:fieldName 目标字段名
 * parma:fieldSearchType 待选数据类型
 * parma:isSearch 是否查询条件
 * parma:isLayer 是否弹出层
 * parma:ischeck 是否可复选、默认单选
 * parma:eachList 联动循环对象
 * parma:tableName 表格名称
 * parma:tableData 表格数据
 */
function getMore(fields, tindex, fieldName, fieldSearchType, isSearch = false, isLayer = false, ischeck = false, eachList = gridColumns ? gridColumns.gridBody : [], tableName = 'dhtable', tableData) {
    console.log('fields:', fields);
    console.log('tindex:', tindex);
    console.log('fieldName:', fieldName);
    console.log('fieldSearchType:', fieldSearchType);
    console.log('isSearch:', isSearch);
    console.log('isLayer:', isLayer);
    console.log('ischeck:', ischeck);
    var obj = $(this), flag = true,
        gClient = $("#gClient").val() || (typeof tindex == 'number' ? (table.cache.dhtable[tindex] ? table.cache.dhtable[tindex].gClient : null) : null),
        gProvider = $("#gProvider").val() || (typeof tindex == 'number' ? (table.cache.dhtable[tindex] ? table.cache.dhtable[tindex].gProvider : null) : null);
    if (fields == 'sCode' && moduleTable == 'TCG_DISTRIBUTION') pCode = table.cache.dhtable[tindex].pCode;

    commodityCode = (typeof tindex == 'number' ? (table.cache.dhtable[tindex] ? table.cache.dhtable[tindex].commodityCode : null) : null);
    if (fieldSearchType && fieldSearchType != 'undefined') {//存在待选数据类型
        if (fieldSearchType.split('_')[1] == 'baseinfo') {//基础数据选择
            var mTitle = '选择' + fieldName, mUrl = '/base/baseinfo/select?vtype=' + fieldSearchType.split('_')[2];
        } else {
            if (fieldSearchType.split('#').length > 1) {//传入的fieldSearchType是字段对应单据路径（fieldFrontExtend1）/hr/recruitmentapply#zpXqNid#招聘需求表
                var mTitle = '选择' + fieldSearchType.split('#')[2], mUrl = fieldSearchType.split('#')[0] + '/select?';
                if ($.inArray(fieldName, ['面试评价表', '入职信息登记表']) > -1) mUrl += "vRzSx=未入职";
            } else {
                switch (fieldSearchType.split('_')[1]) {
                    case 'amazonshop':
                        if (moduleTable == 'TP_FBAPLANORDER') {
                            if (!$('#codeCompany').val()) {
                                layer.msg('公司名称未选择,核实后才在操作!');
                                return
                            } else {
                                var mTitle = '选择' + fieldName,
                                    mUrl = '/hr/amazonshop/select?codeCompany=' + $('#codeCompany').val() + '&authorizeStateFba=1';
                            }
                        } else {//网店信息
                            var mTitle = '选择' + fieldName, mUrl = '/hr/amazonshop/select?deleted=0';
                        }
                        break;
                    case 'operatecompanyapply':
                        var mTitle = '选择' + fieldName, mUrl = '/hr/operatecompanyapply/select?';
                        break;
                    case 'logsticsserver':
                        var mTitle = '选择' + fieldName, mUrl = '/base/logsticsserver/select?';
                        break;
                    case 'logsticspattern':
                        var mTitle = '选择' + fieldName, mUrl = '/business/logsticspattern/select?';
                        break;
                    case 'companyinfo':
                        var mTitle = '选择' + fieldName, mUrl = '/base/company/select?';
                        break;
                    case 'userperformancerule':
                        var mTitle = '选择' + fieldName, mUrl = '/hr/userperformancerule/select?';
                        break;
                    case 'userwelfare':
                        var mTitle = '选择' + fieldName, mUrl = '/hr/userwelfare/select?';
                        break;
                    case 'usersalary':
                        var mTitle = '选择' + fieldName, mUrl = '/hr/usersalary/select?';
                        break;
                    case 'userrank':
                        var mTitle = '选择' + fieldName, mUrl = '/hr/userrank/select?';
                        break;
                    case 'depotinfo':
                        var mTitle = '选择' + fieldName, mUrl = '/system/depot/select?deleted=0';
                        break;
                    case 'purchaseplan'://采购计划
                        if (moduleTable == 'TCG_PURCHASEPLANCANCEL') {
                            console.log("采购取消选择")
                            var mTitle = '选择' + fieldName, mUrl = '/purchase/purchaseplan/select?deleted=0&isOrder=0';
                        } else {
                            var mTitle = '选择' + fieldName, mUrl = '/purchase/purchaseplan/select?deleted=0';
                        }
                        break;
                    case 'purchaseorder'://采购订单
                        if (moduleTable == 'TCG_PURCHASEPLANCANCEL') {
                            console.log("采购取消选择")
                            var mTitle = '选择' + fieldName, mUrl = '/purchase/purchaseplan/select?deleted=0&isOrder=0';
                        } else {
                            var mTitle = '选择' + fieldName, mUrl = '/purchase/purchaseplan/select?deleted=0';
                        }
                        break;
                    case 'orderall'://采购订单
                        var mTitle = '选择' + fieldName, mUrl = '/purchase/purchaseorder/selectAll?deleted=0';
                        break;
                    case 'purchaseaddress'://采购订单
                        var mTitle = '选择' + fieldName, mUrl = '/purchase/purchaseaddress/select?deleted=0';
                        break;
                    case 'purchasingsupplier'://采购供应商备案
                        var mTitle = '选择' + fieldName, mUrl = '/purchase/purchasingsupplier/select?deleted=0';
                        break;
                    case 'offlinepayment'://线下付款
                        var mTitle = '选择' + fieldName, mUrl = '/purchase/offlinepayment/select?deleted=0';
                        break;
                    case 'productactivecomponent'://商品子件
                        var mTitle = '选择' + fieldName, mUrl = '/business/productactive/selectSon?deleted=0';
                        break;
                    case 'productactive'://商品母件
                        var mTitle = '选择' + fieldName, mUrl = '/business/productactive/select?deleted=0';
                        break;
                    case 'assemblyplan'://商品组装方案
                        var mTitle = '选择' + fieldName, mUrl = '/storage/assemblyplan/select?deleted=0';
                        break;
                    case 'goodsallocation'://货位管理
                        var mTitle = '选择' + fieldName, mUrl = '/storage/goodsallocation/select?deleted=0';
                        break;
                    case 'stockcontrol'://库存管理
                        if (moduleTable == 'TCC_STOCKALLOT') {
                            console.log("调拨价大于0")
                            var mTitle = '选择' + fieldName, mUrl = '/storage/stockcontrol/select?deleted=0&allotPrice=0';
                        } else {
                            var mTitle = '选择' + fieldName, mUrl = '/storage/stockcontrol/select?deleted=0';
                        }
                        break;
                    case 'projectmaintenance'://行政维护
                        var mTitle = '选择' + fieldName, mUrl = '/oa/projectmaintenance/select?deleted=0';
                        break;
                    case 'materialmaintenance'://物料维护
                        var mTitle = '选择' + fieldName, mUrl = '/oa/materialmaintenance/select?deleted=0';
                        break;
                    case 'materialpurchaseplan'://物料采购计划
                        var mTitle = '选择' + fieldName, mUrl = '/oa/materialpurchaseplan/select?deleted=0';
                        break;
                    case 'materialassetswarehouse'://物料资产库
                        var mTitle = '选择' + fieldName, mUrl = '/oa/materialassetswarehouse/select?deleted=0';
                        break;
                    case 'userinfo':
                        var mTitle = '选择' + fieldName;
                        // if(fieldName.indexOf("销售") != -1){
                        // 	if(gClient)var mUrl="/system/user/select?roleType=customerGUser&gClient="+gClient;
                        // 	else var mUrl="/system/user/select?roleType=XS";
                        // }else if(fieldName.indexOf("商务") != -1){
                        // 	if(gClient && !['TCRM_CUSTOMERSUSERTRANSFER','TB_CUSTOMERINFO'].includes(moduleTable))var mUrl="/system/user/select?roleType=customerSUser&gClient="+gClient;
                        // 	else var mUrl="/system/user/select?roleType=SW";
                        // }else var mUrl = '/system/user/userselect?', mWidth = '560', mHeight = '465';
                        if (fieldName.indexOf("运营") != -1) {
                            var mUrl = "/system/user/select?roleType=YY";
                        } else {
                            var mUrl = '/system/user/userselect?', mWidth = '560', mHeight = '465';
                        }
                        break;
                    case 'roleinfo':
                        var mTitle = "选择" + fieldName, mUrl = "/system/role/select?";
                        break;
                    case 'organizationinfo':
                        var mTitle = "选择" + fieldName, mUrl = "/system/organization/selectB?";
                        break;
                    default:
                        flag = false;
                        layer.msg('该待选数据类型未处理！', {icon: 7});
                        break;
                }
            }
        }
    } else {//无待选数据类型，特殊处理的弹出框
        switch (fields) {
            case 'gCName':
                var mTitle = '选择客户', mUrl = '/crm/customer/select?blxr=1';//默认查询成交客户，并带出联系人
                //默认查询成交客户，销售报价、商机信息、出差申请查询除黑名单以外客户（成交、潜在）
                if ($.inArray(moduleTable, ['TP_STOCKOFFERPRICE', 'TCRM_BUSINESSINFO', 'THR_ATTENDANCECC']) > -1) mUrl = '/crm/customer/select?stepNameMark=2&blxr=1';
                if (moduleTable == 'TP_STOCKINVOICEOUTORDER') mUrl = '/crm/customer/select?bsp=1';//开票申请需要带出收票人
                break;
            case 'vFkDw'://付款单位
            case 'vSkDw'://收款单位
                var mTitle = '选择' + fieldName, mUrl = '/crm/customer/select?bfkr=1';
                break;
            case 'vManSh'://收货人
            case 'vMan'://联系人
            case 'vKhLxr'://联系人
            case 'vLxr'://联系人
            case 'gUserName'://销售员
                if (gClient) {
                    if (fields == 'vMan' || fields == 'vKhLxr' || fields == 'vLxr' || fields == 'vManSh') {
                        var mTitle = '选择客户联系人', mUrl = '/crm/customerpersion/select?gClient=' + gClient;
                        if (fieldName == '收货人') mUrl += '&includePublic=1';
                    } else if (fields == 'gUserName') {
                        var mTitle = '选择销售员', mUrl = '/crm/customer/userselect?gClient=' + gClient;
                    }
                } else {
                    if (isSearch) {
                        if (fields == 'gUserName') var mTitle = '选择销售员', mUrl = '/crm/customer/userselect?';
                        else var mTitle = '选择客户联系人', mUrl = '/crm/customerpersion/select?';
                    } else {
                        flag = false;
                        layer.msg("请先选择客户！", {icon: 7});
                    }
                }
                break;
            case 'gPName':
                var mTitle = '选择供应商', mUrl = '/crm/provider/select?blxr=1';
                if (moduleTable == 'TP_STOCKINVOICEINORDER' || moduleTable == 'TP_STOCKINVOICEINORDERAB') mUrl = '/crm/provider/select?bsp=1';
                break;
            case 'vPMan'://联系人
            case 'pUserName'://采购员
                if (gProvider) {
                    if (fields == 'vPMan') {
                        var mTitle = '选择供应商联系人', mUrl = '/crm/providerpersion/select?gprovide=' + gProvider;
                    } else if (fields == 'pUserName') {
                        var mTitle = '选择采购员', mUrl = '/crm/provider/userselect?gprovide=' + gProvider;
                    }
                } else {
                    if (isSearch) {
                        if (fields == 'vPMan') var mTitle = '选择供应商联系人', mUrl = '/crm/providerpersion/select?';
                        else var mTitle = '选择采购员', mUrl = '/crm/provider/userselect?';
                    } else {
                        flag = false;
                        layer.msg("请先选择供应商！", {icon: 7});
                    }
                }
                break;
            case 'vSjBh':
                var mTitle = '选择商机信息', mUrl = '/crm/business/select?';
                break;
            case 'htBid':
            case 'vContractId':
                var mTitle = '选择销售合同', mUrl = '/business/bargainin/select?';
                if ($('#vSjBh').val() || $('#vBusinessId').val()) mUrl = '/business/bargainin/select?vSjBh=' + ($('#vSjBh').val() || $('#vBusinessId').val());
                break;
            case 'vXmBm'://项目编码
                var mTitle = '选择项目编码', mUrl = '/business/projectcode/select?deleted=0';
                break;
            case 'vXmMc'://项目名称
                var mTitle = '选择项目', mUrl = '/business/projectadded/select?';
                if ($('#gCName').val()) mUrl = '/business/projectadded/select?gCName=' + $('#gCName').val();
                break;
            case 'zpXqBid'://招聘需求
                var mTitle = '选择招聘需求表', mUrl = '/hr/recruitmentapply/select?';
                break;
            case 'gwBid'://岗位说明书
            case 'gwSmBid':
                var mTitle = '选择岗位说明书', mUrl = '/hr/positioninstructions/select?';
                break;
            case 'msPjBid'://面试评价表
                var mTitle = '选择面试评价表', mUrl = '/hr/interviewresults/select?';
                break;
            case 'rzXxBid'://入职信息登记表
                var mTitle = '选择入职信息登记表', mUrl = '/hr/personnelrzxx/select?';
                break;
            case 'xBid'://人员需求申请
                var mTitle = '选择人员需求列表', mUrl = '/hr/positionrecruitmentapply/select?';
                break;
            case 'dPDate'://周报计划
                var mTitle = '选择对应计划', mUrl = '/crm/weeklyplan/select?deleted=0';
                break;
            case 'vPh'://票据登记
                var mTitle = '选择' + fieldName, mUrl = '/business/invoicemanage/select?deleted=0';
                if (moduleTable == 'TP_STOCKGATHERINGBARGAIN') mUrl += '&bSkBz=0';//合同收款只查询未收款，即收款标志为0
                if (moduleTable == 'TP_STOCKPAYMENTORDER' || moduleTable == 'TP_STOCKPAYMENTORDERAB') mUrl += '&bFkBz=0';//（AB）采购付款只查询未付款，即付款标志为0
                break;
            case 'vHys'://会议室信息
                var mTitle = '选择' + fieldName, mUrl = '/oa/meetingroom/select?deleted=0';
                break;
            case 'fromUserName'://收件人
                var mTitle = '选择' + fieldName, mUrl = '/system/organization/orgObject';
                break;
            case 'userLeader'://用户上级
                var mTitle = '选择用户上级', mUrl = '/system/user/userselect?pagetype=radio', mWidth = "600", mHeight = "470";
                break;
            case 'vGsMcP'://上级公司名称
            case 'vGsMc': //公司名称
            case 'companyName': //公司名称
                var mTitle = '选择运营公司', mUrl = '/hr/operatecompanyapply/select?vGsZt=正常&otherWhere=1';
                break;
            case 'vZnJb'://员工职级
                var mTitle = '选择员工职级', mUrl = '/hr/userrank/select?';
                break;
            case 'partnerName'://合作商账户
                var mTitle = '选择合作商账户', mUrl = '/base/partnerbankinfo/select?';
                break;
            case 'userBankName'://个人银行账户
                var mTitle = '选择个人银行账户', mUrl = '/base/userbankinfo/select?';
                break;
            case 'fNSKU'://fNSKU
                var mTitle = '选择fNSKU', mUrl = '/business/productactive/select2?code=' + $('#productID').val();
                break;
            case 'productID'://fNSKU
                var mTitle = '选择库存', mUrl = '/business/productactive/select?isStock=1';
                break;
            case 'nameCompany'://头程计划公司选择
                var mTitle = '选择备案公司', mUrl = '/hr/operatecompanyapply/select2?' + ($('#bUser').val());
                break;
            case 'sku'://头程计划详情sku选择
                var mTitle = '选择sku信息',
                    mUrl = '/hr/amazonshopproduct/select?code=' + commodityCode + "&shopGuid=" + ($('#sellerId').val());
                break;
            default:
                flag = false;
                layer.msg('该特殊弹出框未处理！', {icon: 7});
                break;
        }
    }
    if (fields == 'gCName' && moduleTable == 'TEDI_SPECIALORDER') mUrl += '&pagetype=checkbox';//单独判断：特价申请，客户选择可多选
    else if (fields == 'sCode' && moduleTable == 'TP_PRODUCTACTIVECOMPONENT') mUrl = '/business/productactive/selectSon?pagetype=checkbox&moduleTable=TP_PRODUCTACTIVECOMPONENT&urltype=userbook', mWidth = '', mHeight = ''; //单独判断：铺货 已选
    else if (fields == 'sCode' && moduleTable == 'TCG_DISTRIBUTION') mUrl = '/business/productactive/selectSon?pagetype=checkbox&moduleTable=TP_PRODUCTACTIVECOMPONENT&urltype=userbook&pcode=' + pCode, mWidth = '', mHeight = ''; //单独判断：铺货 已选
    else {
        if (ischeck) mUrl += '&pagetype=checkbox';//判断是否传入多选参数
        else mUrl += '&pagetype=radio';//默认为单选
    }
    if (flag) {
        console.log("mTitle", mTitle, mUrl)
        $.modal.open(mTitle, mUrl, mWidth, mHeight, function (index) {
            var res = window["layui-layer-iframe" + index].callbackdata();
            if (res == "none" || !res) {//没有选中时
                layer.msg("请选择！", {icon: 7});
            } else {
                console.log('选择的数据', res);
                var fieldsList = {};//目标字段及数据源字段对象
                if (isSearch) {//如果是查询列表则不需要联动赋值
                    $.each(gridColumns.dictionaryForPageFieldList, function (i, v) {
                        if (v.fields == fields) $('#' + fields).val(res[v.fieldFrontSave]);
                    })
                } else { //非查询列表的弹出框
                    if (typeof tindex == "number") {//明细中的弹出框
                        tableData = (typeof table == 'undefined') ? (noTable.length > 0 ? noTable : [{'nid': 0}]) : table.cache.dhtable;//没有定义table以及为制单状态时
                        $.each(tableData, function (i, v) { //修复排序后下标错误的问题
                            if (v.LAY_TABLE_INDEX == tindex) {
                                tindex = i;
                                return false;
                            }
                        })
                        console.log("eachList,fieldsList,fields", eachList, fieldsList, fields)
                        fieldsList = getFieldMatchedList(eachList, fieldsList, fields);//循环遍历获取联动字段
                        console.log("循环遍历获取联动字段", fieldsList)
                        $.each(fieldsList, function (i, v) {//直接通过dom修改而不再重载
                            tableData[tindex][i] = res[v];
                            setTableValue(tableName, tindex, i, res[v]);
                        });
                        if (table.cache.dhtable_c) table.reload('dhtable_c', {data: table.cache.dhtable});//重新渲染弹出框的子表
                        if (typeof getMoreAfter == 'function') getMoreAfter(fieldsList, fields, tindex, fieldName, fieldSearchType, isSearch, isLayer, res);//弹出框赋值回调
                        console.log('赋值对象1', fieldsList);//联动字段对象
                    } else {//非明细的弹出框（无表格下标）

                        if (isLayer) {//是否弹出层
                            // console.log(gridColumns.gridBody);
                            // fieldsList=getFieldMatchedList(gridColumns.gridBody,fieldsList,fields);//循环遍历获取联动字段
                            fieldsList = getFieldMatchedList((typeof all_fields == 'undefined') ? gridColumns.gridBody : all_fields.concat(gridColumns.gridBody), fieldsList, fields);//循环遍历获取联动字段
                        } else {//非弹出层中的弹出框（普通单据的弹出框）
                            if (gridColumns) {
                                // if(moduleTable!='TCG_DISTRIBUTION'){
                                var eachFields = (typeof all_fields == 'undefined') ? gridColumns.dictionaryForPageFieldList : all_fields;
                                // }else{
                                // 	var eachFields=(typeof all_fields == 'undefined')?zjgridColumns.dictionaryForPageFieldList:all_fields;
                                // }
                            } else {
                                var eachFields = (typeof all_fields == 'undefined') ? [] : all_fields;
                            }
                            console.log("eachFields", eachFields, fieldsList)
                            fieldsList = getFieldMatchedList(eachFields, fieldsList, fields);//循环遍历获取联动字段
                        }
                        $.each(fieldsList, function (i, v) {//表头联动赋值
                            if (isLayer) $('.layui-layer #' + i).val(res[v]);
                            else $("#" + i).val(res[v]);
                        });
                        if (typeof getMoreAfter == 'function') getMoreAfter(fieldsList, fields, tindex, fieldName, fieldSearchType, isSearch, isLayer, res);//弹出框赋值回调
                        console.log('赋值对象2', fieldsList);//联动字段对象
                    }
                }
                layer.close(index);
            }
        });
    }
}

/* 循环遍历获取联动字段（默认为三层联动，太长超出运算范围）
 * parma:eachList 循环遍历对象
 * parma:fieldsList 存放联动字段对象
 * parma:fields 触发联动的字段
 */
function getFieldMatchedList(eachList, fieldsList, fields) {
    console.log("fields", fields)
    var vfield1, vfield2, vfield3;//取当前字段名(表头的字段名与明细的字段名存放位置不同)
    $.each(eachList, function (i, v) {//第一次循环，判断联动：找到自己及联动
        vfield1 = v.fields ? v.fields : v.field;
        if (v.fieldMatched == fields || vfield1 == fields) {//自己和第一层联动
            if (v.fieldFrontType && v.fieldFrontType.indexOf('t_buttontext') != -1 && vfield1 != fields) {//弹出窗控件且不是触发字段
                fieldsList[vfield1] = (v.fieldFrontShow ? v.fieldFrontShow : v.fieldFrontSave);
                $.each(eachList, function (i2, v2) {//第二次循环，判断联动：找到儿子联动
                    if (v2.fieldMatched == vfield1) {
                        vfield2 = v2.fields ? v2.fields : v2.field;
                        fieldsList[vfield2] = (v2.fieldFrontShow ? v2.fieldFrontShow : v2.fieldFrontSave);
                        if (v2.fieldFrontType && v2.fieldFrontType.indexOf('t_buttontext') != -1) $.each(eachList, function (i3, v3) {//第三次循环，判断联动：找到孙子联动
                            vfield3 = v3.fields ? v3.fields : v3.field;
                            if (v3.fieldMatched == vfield2) fieldsList[vfield3] = (v3.fieldFrontShow ? v3.fieldFrontShow : v3.fieldFrontSave);
                        });
                    }
                });
            } else fieldsList[vfield1] = fieldsList[vfield1] ? fieldsList[vfield1] : v.fieldFrontSave;
        }
    });
    return fieldsList;
}

/*
 * 	弹出框控件打开对应单据页面（小眼睛）
 *	parma:id 当前dom对象id
 *	parma:url 对应单据路径、单据nid字段、单据名称，形如：hr/positioninstructions#gwSmNid#岗位说明书，太长thymeleaf会报错，所以去除通用"/edit?nid="
 */
function openDetailBusiness(id, url) {
    if ($('#' + id).val()) {//当前dom控件内容不为空
        parent.layui.index.openTabsPage(url.split('#')[0] + '/edit?nid=' + $('#' + url.split('#')[1]).val(), url.split('#')[2] + '(' + $('#' + id).val() + ')');
    } else {
        layer.msg("尚未选择！", {icon: 5});
    }
}

//操作日志
function oplog(guid) {
    $.get('/common/updatelog/selectLog', {moduleGuid: guid}, function (res) {
        var datalist = res.data.list
        var colslist = res.data.gridColumns.gridBody
        $.tablelist.init({
            elem: '#pdhtable'
            , data: datalist
            , limit: 99999
            , totalRow: false
            , cols: [colslist]
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , page: false
            , done: function (res, curr, count) {
                var ltv = this.elem.next('.layui-table-view');//当前table的dom
                res.data.length || count || ltv.find('.layui-table-header').css('display', 'inline-block');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
                res.data.length || count || ltv.find('.layui-table-box').css('overflow-x', 'auto');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
                res.data.length || count || ltv.find('.layui-table-body').css('height', ltv.find('.layui-table-body').height() - 17);//数量为0时，表格高度减少滚动条高度
                $('.spxx').show()
                $('.layui-table-body.layui-table-main').eq(0).css('height', "35vh");
                $('.layui-table-body.layui-table-main').eq(1).css('height', "30vh");
                $('.layui-table-body').eq(1).css('height', "calc(35vh - 15px)");
                if (['TCG_PURCHASEORDER'].includes(moduleTable)) $('.layui-table-body').eq(2).css('height', "calc(35vh - 15px)");
                fixTotal(this);//修复合计行固定列问题
                if (typeof listTableDone == 'function') listTableDone();//如果查询列表存在表格加载完成回调事件，则执行
            }
            , jump: function (obj, first) {
            }
        })
        // table.reload('pdhtable', {data:res.data.list,cols:[res.data.gridColumns.gridBody]});
    });
}

// 公共表头1
function headcom() {
    var str = `<div class="layui-form layui-card-header layuiadmin-card-header-auto">
		<div class="layui-form-item margin_t0">`
    $.each(fieldsList, function (i, v) {
        str += `<div class="layui-inline margin_r0 ${v.fieldFrontTopSize == 1 ? 'layui-col-xs4' : (v.fieldFrontTopSize == 2 ? 'layui-col-xs8' : 'layui-col-xs12')}">
	    		    <label class="layui-form-label">`
        if (v.fieldFrontRequired) {
            str += `<font class="f_red">*</font>`
        }
        str += `<font>${v.fieldName}：</font>
	    		    </label>
	    		    <div class="layui-input-block">`
        if (v.fieldFrontType == 't_text') str += `<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="${v.fieldFrontEdit ? 'layui-input' : 'layui-input canntEdit'}" lay-verify="${v.fieldFrontRequired ? 'required' : ''}" autocomplete="off" onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
        if (v.fieldFrontType == 't_decimal') str += `<input type="${v.fieldFrontEdit ? 'number' : 'text'}" value="${v.fieldContent}" name="${v.fields}" id="${v.fields}"  class="${v.fieldFrontEdit ? 'layui-input' : 'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
        if (v.fieldFrontType == 't_date' || v.fieldFrontType == 't_datetime' || v.fieldFrontType == 't_year' || v.fieldFrontType == 't_monthly') {
            str += `<input type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  datetype="${v.fieldFrontType}" class="${v.fieldFrontEdit ? 'layui-input t_date' : 'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
            str += `<i id="${v.fields}_date" class="dhicon dh-calendar icon_date_business" style="font-size:0"></i>`
        }
        if (v.fieldFrontType == 't_buttontext') {
            str += `<input type="text" class="${v.fieldFrontEdit ? 'layui-input buttontext' : 'layui-input canntEdit'}" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" autocomplete="off" readonly onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}"/>`
            if (v.fieldFrontEdit) {
                str += `<i class="layui-icon layui-icon-more getMore" onclick="getMore('${v.fields}',null,'${v.fieldName}','${v.fieldSearchType}',false,false)" getType="${v.fields}"></i>`
            }
        }
        if (v.fieldFrontType == 't_dropdown') {
            if (v.fieldFrontEdit) {
                str += `<select type="text" id="${v.fields}" name="${v.fields}" autocomplete="off" class="layui-select" lay-search lay-filter="select_top" data-fieldMatched="${v.fieldMatched}" data-fieldFrontSave="${v.fieldFrontSave}" data-fieldFrontShow="${v.fieldFrontShow}">
					     		<option></option>`
                if (v.dropdownList) {
                    for (var i = 0; i < v.dropdownList.length; i++) {
                        str += `<option text="${v.dropdownList[i].vname}" value="${v.dropdownList[i].vid}" ${v.dropdownList[i].vname == v.fieldContent ? 'selected' : ''} data-vremark="${v.dropdownList[i].vremark}" data-fvalue="${v.dropdownList[i].fvalue}">${v.dropdownList[i].vname}</option>`
                    }
                }
                str += `</select>`
            } else {
                str += `<input  type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  class="layui-input canntEdit" autocomplete="off" readonly>`
            }
        }
        if (v.fieldFrontType == 't_textarea') str += `<textarea name="${v.fields}" id="${v.fields}" class="${v.fieldFrontEdit}?'layui-textarea':'layui-textarea canntEdit'" onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}"  ${v.fieldFrontEdit ? '' : 'readonly'}>${v.fieldContent}</textarea>`

        if (v.fieldFrontType == 't_file2') {
            str += `<div class="layui-upload-drag fieldsimg" name="${v.fields}" id="${v.fields}_upimg">
	    					<input type="hidden" id="${v.fields}" name="${v.fields}" value="${v.fieldContent}"/>
	    					<div class="${v.fieldContent ? 'layui-hide upicon' : 'upicon'}">
	    						<i class="layui-icon"></i>
	    						<p>点击上传图片</p>
	    					</div>
	    					
	    					<div class="${v.fieldContent ? '' : 'layui-hide'}" id="uploadDemoView">
	    					  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
	    					</div>
	    				</div>`
        }

        str += `</div></div>`

    })
    str += `</div></div>`

    $.each(fieldsHiddenList, function (i, v) {
        str += `<input type="hidden" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}">`
    })
    $('.forminput').html(str)
    form.render();
}

// 公共表头2
function headcom2() {
    var str = `<div class="layui-form layui-card-header layuiadmin-card-header-auto">
	<div class="layui-form-item margin_t0">`
    $.each(fieldsList, function (i, v) {
        if (v.fields == 'code') code = v.fieldContent
        if (enableEdit == 1) {
            str += `<div class="layui-inline margin_r0 ${v.fieldFrontTopSize == 1 ? 'layui-col-xs4' : (v.fieldFrontTopSize == 2 ? 'layui-col-xs8' : 'layui-col-xs12')}">
				<label class="layui-form-label">`
            if (v.fieldFrontRequired) {
                str += `<font class="f_red">*</font>`
            }
            str += `<font>${v.fieldName}：</font>
				</label>
				<div class="layui-input-block">`
            if (v.fieldFrontType == 't_text') str += `<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="${v.fieldFrontEdit ? 'layui-input' : 'layui-input canntEdit'}" lay-verify="${v.fieldFrontRequired ? 'required' : ''}" autocomplete="off" onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
            if (v.fieldFrontType == 't_decimal') str += `<input type="${v.fieldFrontEdit ? 'number' : 'text'}" value="${v.fieldContent}" name="${v.fields}" id="${v.fields}"  class="${v.fieldFrontEdit ? 'layui-input' : 'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
            if (v.fieldFrontType == 't_date' || v.fieldFrontType == 't_datetime' || v.fieldFrontType == 't_year' || v.fieldFrontType == 't_monthly') {
                str += `<input type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  datetype="${v.fieldFrontType}" class="${v.fieldFrontEdit ? 'layui-input t_date' : 'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
                str += `<i id="${v.fields}_date" class="dhicon dh-calendar icon_date_business" style="font-size:0"></i>`
            }
            if (v.fieldFrontType == 't_buttontext') {
                str += `<input type="text" class="${v.fieldFrontEdit ? 'layui-input buttontext' : 'layui-input canntEdit'}" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" autocomplete="off" readonly onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}"/>`
                if (v.fieldFrontEdit) {
                    str += `<i class="layui-icon layui-icon-more getMore" onclick="getMore('${v.fields}',null,'${v.fieldName}','${v.fieldSearchType}',false,false)" getType="${v.fields}"></i>`
                }
            }
            if (v.fieldFrontType == 't_dropdown') {
                if (v.fieldFrontEdit) {
                    str += `<select type="text" id="${v.fields}" name="${v.fields}" autocomplete="off" class="layui-select" lay-search lay-filter="select_top" data-fieldMatched="${v.fieldMatched}" data-fieldFrontSave="${v.fieldFrontSave}" data-fieldFrontShow="${v.fieldFrontShow}">
							 <option></option>`
                    if (v.dropdownList) {
                        for (var i = 0; i < v.dropdownList.length; i++) {
                            str += `<option text="${v.dropdownList[i].vname}" value="${v.dropdownList[i].vid}" ${v.dropdownList[i].vname == v.fieldContent ? 'selected' : ''} data-vremark="${v.dropdownList[i].vremark}" data-fvalue="${v.dropdownList[i].fvalue}">${v.dropdownList[i].vname}</option>`
                        }
                    }
                    str += `</select>`
                } else {
                    str += `<input  type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  class="layui-input canntEdit" autocomplete="off" readonly>`
                }
            }
            if (v.fieldFrontType == 't_textarea') str += `<textarea name="${v.fields}" id="${v.fields}" class="${v.fieldFrontEdit}?'layui-textarea':'layui-textarea canntEdit'" onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}"  ${v.fieldFrontEdit ? '' : 'readonly'}>${v.fieldContent}</textarea>`

            if (v.fieldFrontType == 't_file2') {
                str += `<div class="layui-upload-drag fieldsimg" name="${v.fields}" id="${v.fields}_upimg">
						<input type="hidden" id="${v.fields}" name="${v.fields}" value="${v.fieldContent}"/>
						<div class="${v.fieldContent ? 'layui-hide upicon' : 'upicon'}">
							<i class="layui-icon"></i>
							<p>点击上传图片</p>
						</div>
						
						<div class="${v.fieldContent ? '' : 'layui-hide'}" id="uploadDemoView">
						  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
						</div>.
					</div>`
            }

            str += `</div></div>`
        } else {
            str += `<div class="layui-inline margin_r0 ${v.fieldFrontTopSize == 1 ? 'layui-col-xs4' : (v.fieldFrontTopSize == 2 ? 'layui-col-xs8' : 'layui-col-xs12')}">
				<label class="layui-form-label">`
            if (v.fieldFrontRequired) {
                str += `<font class="f_red">*</font>`
            }
            str += `<font>${v.fieldName}：</font>
				</label>
				<div class="layui-input-block">`

            if (v.fieldFrontType == 't_textarea') {
                str += `<textarea name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="layui-textarea canntEdit" readonly}></textarea>`
            } else if (v.fieldFrontType == 't_file2') {
                str += `<div class="layui-upload-drag fieldsimg" name="${v.fields}">
						<input type="hidden" id="${v.fields}" name="${v.fields}"/>
						<div class="${v.fieldContent ? '' : 'layui-hide'}" id="uploadDemoView">
						  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
						</div>.
					</div>`
            } else {
                str += `<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="layui-input canntEdit" lay-verify="${v.fieldFrontRequired ? 'required' : ''}" autocomplete="off" readonly>`
            }
            str += `</div></div>`
        }
    })
    str += `</div></div>`
    $.each(fieldsHiddenList, function (i, v) {
        str += `<input type="hidden" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}">`
    })
    $('.forminput').html(str)
    form.render();
}

// 公共表头3
function headcom3() {
    var str = `<div class="layui-form layui-card-header layuiadmin-card-header-auto">
	<div class="layui-form-item margin_t0">`
    $.each(fieldsList, function (i, v) {
        if (enableEdit == 1) {
            str += `<div class="layui-inline margin_r0 ${v.fieldFrontTopSize == 1 ? 'layui-col-xs4' : (v.fieldFrontTopSize == 2 ? 'layui-col-xs8' : 'layui-col-xs12')}">
				<label class="layui-form-label">`
            if (v.fieldFrontRequired) {
                str += `<font class="f_red">*</font>`
            }
            str += `<font>${v.fieldName}：</font>
				</label>
				<div class="layui-input-block">`
            if (v.fieldFrontType == 't_text') str += `<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="${v.fieldFrontEdit ? 'layui-input' : 'layui-input canntEdit'}" lay-verify="${v.fieldFrontRequired ? 'required' : ''}" autocomplete="off" onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
            if (v.fieldFrontType == 't_decimal') str += `<input type="${v.fieldFrontEdit ? 'number' : 'text'}" value="${v.fieldContent}" name="${v.fields}" id="${v.fields}"  class="${v.fieldFrontEdit ? 'layui-input' : 'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
            if (v.fieldFrontType == 't_date' || v.fieldFrontType == 't_datetime' || v.fieldFrontType == 't_year' || v.fieldFrontType == 't_monthly') {
                str += `<input type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  datetype="${v.fieldFrontType}" class="${v.fieldFrontEdit ? 'layui-input t_date' : 'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}" ${v.fieldFrontEdit ? '' : 'readonly'}>`
                str += `<i id="${v.fields}_date" class="dhicon dh-calendar icon_date_business" style="font-size:0"></i>`
            }
            if (v.fieldFrontType == 't_buttontext') {
                str += `<input type="text" class="${v.fieldFrontEdit ? 'layui-input buttontext' : 'layui-input canntEdit'}" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" autocomplete="off" readonly onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}"/>`
                if (v.fieldFrontEdit) {
                    str += `<i class="layui-icon layui-icon-more getMore" onclick="getMore('${v.fields}',null,'${v.fieldName}','${v.fieldSearchType}',false,false)" getType="${v.fields}"></i>`
                }
            }
            if (v.fieldFrontType == 't_dropdown') {
                if (v.fieldFrontEdit) {
                    str += `<select type="text" id="${v.fields}" name="${v.fields}" autocomplete="off" class="layui-select" lay-search lay-filter="select_top" data-fieldMatched="${v.fieldMatched}" data-fieldFrontSave="${v.fieldFrontSave}" data-fieldFrontShow="${v.fieldFrontShow}">
							 <option></option>`
                    if (v.dropdownList) {
                        for (var i = 0; i < v.dropdownList.length; i++) {
                            str += `<option text="${v.dropdownList[i].vname}" value="${v.dropdownList[i].vid}" ${v.dropdownList[i].vname == v.fieldContent ? 'selected' : ''} data-vremark="${v.dropdownList[i].vremark}" data-fvalue="${v.dropdownList[i].fvalue}">${v.dropdownList[i].vname}</option>`
                        }
                    }
                    str += `</select>`
                } else {
                    str += `<input  type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  class="layui-input canntEdit" autocomplete="off" readonly>`
                }
            }
            if (v.fieldFrontType == 't_textarea') str += `<textarea name="${v.fields}" id="${v.fields}" class="${v.fieldFrontEdit}?'layui-textarea':'layui-textarea canntEdit'" onblur="${v.fieldFrontRequired ? 'inputOnBlur(this)' : ''}"  ${v.fieldFrontEdit ? '' : 'readonly'}>${v.fieldContent}</textarea>`

            if (v.fieldFrontType == 't_file2') {
                str += `<div class="layui-upload-drag fieldsimg" name="${v.fields}" id="${v.fields}_upimg">
						<input type="hidden" id="${v.fields}" name="${v.fields}" value="${v.fieldContent}"/>
						<div class="${v.fieldContent ? 'layui-hide upicon' : 'upicon'}">
							<i class="layui-icon"></i>
							<p>点击上传图片</p>
						</div>
						
						<div class="${v.fieldContent ? '' : 'layui-hide'}" id="uploadDemoView">
						  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
						</div>.
					</div>`
            }

            if (v.fieldFrontType == 't_file') {
                str += `<input type="text" class="layui-input buttontext" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" readonly/><i class="layui-icon layui-icon-upload getUpload" onclick="getUpload([[${v.fields}]],'Head','','',[[${v.fieldFrontValue}]]);" getType="${v.fields}"></i>`
            }

            str += `</div></div>`
        } else {
            str += `<div class="layui-inline margin_r0 ${v.fieldFrontTopSize == 1 ? 'layui-col-sm4' : (v.fieldFrontTopSize == 2 ? 'layui-col-sm8' : 'layui-col-sm12')}">
				<label class="layui-form-label">`
            if (v.fieldFrontRequired) {
                str += `<font class="f_red">*</font>`
            }
            str += `<font>${v.fieldName}：</font>
				</label>
				<div class="layui-input-block">`

            if (v.fieldFrontType == 't_textarea') {
                str += `<textarea name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="layui-textarea canntEdit" readonly}></textarea>`
            } else if (v.fieldFrontType == 't_file2') {
                str += `<div class="layui-upload-drag fieldsimg" name="${v.fields}">
						<input type="hidden" id="${v.fields}" name="${v.fields}"/>
						<div class="${v.fieldContent ? '' : 'layui-hide'}" id="uploadDemoView">
						  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
						</div>.
					</div>`
            } else {
                str += `<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="layui-input canntEdit" lay-verify="${v.fieldFrontRequired ? 'required' : ''}" autocomplete="off" readonly>`
            }
            str += `</div></div>`
        }
    })
    str += `</div></div>`
    $.each(fieldsHiddenList, function (i, v) {
        str += `<input type="hidden" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}">`
    })
    $.each(b_fields, function (i, v) {
        str += `<input type="hidden" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}">`
    })
    $('.forminput').html(str)
    form.render();
}

function assemblyhead() {
    $(".fieldsimg").each(function () {
        var id = $(this).attr('name')
        upload.render({
            elem: '#' + id + '_upimg',
            url: window.updateurls + '/system/fileinfo/uploadmailimg',
            accept: 'images',
            before: function (obj) {
                this.data = {
                    'moduleFile': 'images'
                }
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    console.log(index, file, result)
                });
            },
            done: function (res) {
                //如果上传失败
                if (res.errno > 0) {
                    return layer.msg('上传失败');
                } else {
                    if (res.code == 500) {
                        return layer.msg(res.msg);
                    } else {
                        layer.msg('上传成功');
                        $('#' + id).val(window.updateurls + res.data[0])
                        layui.$('#' + id + '_upimg').find('.upicon').addClass('layui-hide')
                        layui.$('#' + id + '_upimg').find('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', window.updateurls + res.data[0]);
                    }
                }
            }, error: function (err) {
                //演示失败状态，并实现重传
                console.log(err)
            }
        });
    })


    $('.t_date').each(function () {
        var datetype = $(this).attr('datetype')
        laydate.render({
            elem: this
            ,
            type: datetype == 't_date' ? 'date' : datetype == 't_datetime' ? 'datetime' : datetype == 't_year' ? 'year' : 'month'
        })
    })
}

//月份
function formatTime(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    return [year, month].map(formatNumber).join('-');
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

//图片放大
function firstimg() {
    $("body img").mouseenter(function () {
        var aimgurl = $(this).attr('src')
        $('.ishide').show()
        $('.bagimg').css({position: 'absolute', top: $(this).offset().top, left: $(this).offset().left + 32})
        $('.bagimg').attr('src', aimgurl)

    });
    $("body img").mouseleave(function () {
        $('.ishide').hide()
    });
}

// 筛选1个数组相同的数据
window.newData = function (arr) {
    const map = {};
    arr.forEach(item => {
        const obj = {};
        Object.keys(item).sort().map(key => obj[key] = item[key]);
        map[JSON.stringify(obj)] = item;
    });
    return Object.keys(map).map(key => JSON.parse(key));
}

// 筛选2个数组相同的数据
window.delData = function (data, deldata) {
    data.forEach(item => {
        deldata = deldata.filter(items => items.guid != item.guid);
    });
    return deldata;
}